package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.traceable.TraceableOrder;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.traceable.TraceableGroup;
import com.zbkj.service.dao.TraceableGroupDao;
import com.zbkj.service.service.TraceableGroupService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description TraceableGroupServiceImpl 接口实现
* @date 2025-07-08
*/
@Service
public class TraceableGroupServiceImpl extends ServiceImpl<TraceableGroupDao, TraceableGroup> implements TraceableGroupService {

    @Resource
    private TraceableGroupDao dao;

    @Override
    public Boolean createPlatform(TraceableGroupSaveRequest traceableGroupSaveRequest) {
        TraceableGroup traceableGroup = new TraceableGroup();
        BeanUtils.copyProperties(traceableGroupSaveRequest, traceableGroup, "id");
        traceableGroup.setBrandId(BrandUtil.getBrandIdByUrl());
        boolean save = save(traceableGroup);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    @Override
    public Boolean createBrand(TraceableGroupSaveRequest traceableGroupSaveRequest) {
        TraceableGroup traceableGroup = new TraceableGroup();
        BeanUtils.copyProperties(traceableGroupSaveRequest, traceableGroup, "id");
        traceableGroup.setBrandId(BrandUtil.getBrandIdByUrl());
        boolean save = save(traceableGroup);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询溯源套餐表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<TraceableGroup>
     * @author dazongzi
     * @since 2025-07-08
     */
    @Override
    public List<TraceableGroupBrandPageDataResponse> getListBrand(TraceableGroupBrandSearchRequest request, PageParamRequest pageParamRequest) {
        // 先拿总平台的数据
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带 TraceableGroup 类的多条件查询
        LambdaQueryWrapper<TraceableGroup> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(TraceableGroup::getBrandId, 0);
        lambdaQueryWrapper.eq(TraceableGroup::getIsDel, false);
        if (ObjectUtil.isNotEmpty(request.getName())) {
            lambdaQueryWrapper.like(TraceableGroup::getName, URLUtil.decode(request.getName()));
        }
        lambdaQueryWrapper.orderByDesc(TraceableGroup::getCreateTime);
        List<TraceableGroup> traceableGroups = dao.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(traceableGroups)) {
            return new ArrayList<>();
        }
        List<TraceableGroupBrandPageDataResponse> traceableGroupResponses = new ArrayList<>();

        // 当前品牌商的数据
        List<Integer> ids = traceableGroups.stream().map(TraceableGroup::getId).distinct().collect(Collectors.toList());

        List<TraceableGroup> brandTraceableGroups = getBrandDataList(ids);

        traceableGroups.stream().forEach(x->{
            TraceableGroupBrandPageDataResponse traceableGroupResponse = new TraceableGroupBrandPageDataResponse();
            BeanUtils.copyProperties(x, traceableGroupResponse);
            traceableGroupResponse.setPlatformMiniNum(x.getMiniNum());
            traceableGroupResponse.setPlatformPrice(x.getPrice());
            // 赋值当前品牌商的数据
            setCurBrandData(traceableGroupResponse, brandTraceableGroups);
            traceableGroupResponses.add(traceableGroupResponse);
        });
        return traceableGroupResponses;
    }

    private void setCurBrandData(TraceableGroupBrandPageDataResponse group, List<TraceableGroup> brandTraceableGroups) {
        brandTraceableGroups.stream().forEach(brandGroup -> {
            if (brandGroup.getSourceId().equals(group.getId())) {
                group.setPrice(brandGroup.getPrice());
                group.setMiniNum(brandGroup.getMiniNum());
                group.setStatus(brandGroup.getStatus());
                group.setUpdateTime(brandGroup.getUpdateTime());
            }
        });
    }

    private List<TraceableGroup> getBrandDataList(List<Integer> ids) {
        LambdaQueryWrapper<TraceableGroup> lqw = Wrappers.lambdaQuery();
        lqw.in(TraceableGroup::getSourceId, ids);
        lqw.eq(TraceableGroup::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.eq(TraceableGroup::getIsDel, false);
        return list(lqw);
    }

    /**
     * 分页查询溯源套餐表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<TraceableGroup>
     * @author dazongzi
     * @since 2025-07-08
     */
    @Override
    public List<TraceableGroupPageDataResponse> getListPlatform(TraceableGroupSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 TraceableGroup 类的多条件查询
        LambdaQueryWrapper<TraceableGroup> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(TraceableGroup::getBrandId, BrandUtil.getBrandIdByUrl());
        if (ObjectUtil.isNotEmpty(request.getName())) {
            lambdaQueryWrapper.like(TraceableGroup::getName, URLUtil.decode(request.getName()));
        }
        if (ObjectUtil.isNotEmpty(request.getStatus()) && request.getStatus() > 0) {
            lambdaQueryWrapper.eq(TraceableGroup::getId, request.getStatus());
        }
        lambdaQueryWrapper.orderByDesc(TraceableGroup::getCreateTime);
        List<TraceableGroup> traceableGroups = dao.selectList(lambdaQueryWrapper);
        List<TraceableGroupPageDataResponse> traceableGroupResponses = new ArrayList<>();

        traceableGroups.stream().forEach(x->{
            TraceableGroupPageDataResponse traceableGroupResponse = new TraceableGroupPageDataResponse();
            BeanUtils.copyProperties(x, traceableGroupResponse);
            traceableGroupResponses.add(traceableGroupResponse);
        });
        return traceableGroupResponses;
    }

    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<TraceableGroup> luw = Wrappers.lambdaUpdate();
        luw.set(TraceableGroup::getIsDel, true);
        luw.in(TraceableGroup::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除溯源套餐失败"));
        }
        return true;
    }

    @Override
    public boolean updatePlatform(TraceableGroupSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入溯源套餐ID");
        }
        getByIdException(request.getId());
        TraceableGroup traceableGroup = new TraceableGroup();
        BeanUtils.copyProperties(request, traceableGroup);
        return updateById(traceableGroup);
    }

    @Override
    public boolean updateBrand(TraceableGroupSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入溯源套餐ID");
        }
        TraceableGroup parentGroup = getByIdException(request.getId());
        TraceableGroup traceableGroup = this.getOne(new LambdaQueryWrapper<TraceableGroup>()
                .eq(TraceableGroup::getIsDel, false)
                .eq(TraceableGroup::getBrandId, BrandUtil.getBrandIdByUrl())
                .eq(TraceableGroup::getSourceId, request.getId()));
        if (ObjectUtil.isNull(traceableGroup)) {
            traceableGroup = new TraceableGroup();
            traceableGroup.setPrice(request.getPrice());
            traceableGroup.setStatus(request.getStatus());
            traceableGroup.setMiniNum(request.getMiniNum());
            traceableGroup.setSourceId(parentGroup.getId());
            traceableGroup.setName(parentGroup.getName());
            traceableGroup.setBrandId(BrandUtil.getBrandIdByUrl());
            return save(traceableGroup);
        } else {
            TraceableGroup traceableGroupTmp = new TraceableGroup();
            traceableGroupTmp.setId(traceableGroup.getId());
            if (ObjectUtil.isNotNull(request.getPrice())) {
                traceableGroupTmp.setPrice(request.getPrice());
            }
            if (ObjectUtil.isNotNull(request.getStatus())) {
                traceableGroupTmp.setStatus(request.getStatus());
            }
            if (ObjectUtil.isNotNull(request.getMiniNum())) {
                traceableGroupTmp.setMiniNum(request.getMiniNum());
            }
            return updateById(traceableGroupTmp);
        }
    }

    @Override
    public TraceableGroupDetailResponse getDetailsPlatform(Integer id) {
        LambdaQueryWrapper<TraceableGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(TraceableGroup::getIsDel, 0);
        lqw.eq(TraceableGroup::getBrandId, 0);
        lqw.last("limit 1");
        TraceableGroup traceableGroup = this.getOne(lqw);
        if (ObjectUtil.isNotNull(traceableGroup)) {
            TraceableGroupDetailResponse response = new TraceableGroupDetailResponse();
            BeanUtils.copyProperties(traceableGroup, response);
            return response;
        }
        return null;
    }

    @Override
    public TraceableGroupDetailResponse getDetailsBrand(Integer id) {
        LambdaQueryWrapper<TraceableGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(TraceableGroup::getIsDel, 0);
        lqw.eq(TraceableGroup::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.last("limit 1");
        TraceableGroup traceableGroup = this.getOne(lqw);
        if (ObjectUtil.isNotNull(traceableGroup)) {
            TraceableGroupDetailResponse response = new TraceableGroupDetailResponse();
            BeanUtils.copyProperties(traceableGroup, response);
            return response;
        }
        return null;
    }

    @Override
    public TraceableGroup getBrandGroup(Integer id) {
        LambdaQueryWrapper<TraceableGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(TraceableGroup::getIsDel, false);
        lqw.eq(TraceableGroup::getSourceId, id);
        lqw.eq(TraceableGroup::getStatus, 1);
        lqw.eq(TraceableGroup::getBrandId, BrandUtil.getBrandIdByUrl());
        return getOne(lqw);
    }

    @Override
    public TraceableGroup getPlatformGroup(Integer id) {
        LambdaQueryWrapper<TraceableGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(TraceableGroup::getIsDel, false);
        lqw.eq(TraceableGroup::getStatus, 1);
        lqw.eq(TraceableGroup::getBrandId, 0);
        lqw.eq(TraceableGroup::getId, id);
        return getOne(lqw);
    }

    @Override
    public PageInfo<TraceableGroupFrontSearchResponse> getListFront(TraceableGroupFrontSearchRequest request, PageParamRequest pageParamRequest) {
        Page<TraceableOrder> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带 TraceableGroup 类的多条件查询
        LambdaQueryWrapper<TraceableGroup> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(TraceableGroup::getBrandId, 0);
        lambdaQueryWrapper.eq(TraceableGroup::getIsDel, false);
        if (ObjectUtil.isNotEmpty(request.getName())) {
            lambdaQueryWrapper.like(TraceableGroup::getName, URLUtil.decode(request.getName()));
        }
        lambdaQueryWrapper.orderByDesc(TraceableGroup::getCreateTime);
        List<TraceableGroup> traceableGroups = dao.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(traceableGroups)) {
            return CommonPage.copyPageInfo(page, new ArrayList<>());
        }
        List<TraceableGroupFrontSearchResponse> traceableGroupResponses = new ArrayList<>();

        // 当前品牌商的数据
        List<Integer> ids = traceableGroups.stream().map(TraceableGroup::getId).distinct().collect(Collectors.toList());

        List<TraceableGroup> brandTraceableGroups = getBrandDataList(ids);

        traceableGroups.stream().forEach(x->{
            TraceableGroupFrontSearchResponse traceableGroupResponse = new TraceableGroupFrontSearchResponse();
            BeanUtils.copyProperties(x, traceableGroupResponse);
            // 赋值当前品牌商的数据
            setCurBrandData(traceableGroupResponse, brandTraceableGroups);
            traceableGroupResponses.add(traceableGroupResponse);
        });
        return CommonPage.copyPageInfo(page, traceableGroupResponses);
    }

    private void setCurBrandData(TraceableGroupFrontSearchResponse group, List<TraceableGroup> brandTraceableGroups) {
        brandTraceableGroups.stream().forEach(brandGroup -> {
            if (brandGroup.getSourceId().equals(group.getId())) {
                group.setPrice(brandGroup.getPrice());
                group.setMiniNum(brandGroup.getMiniNum());
            }
        });
    }

    private TraceableGroup getByIdException(Integer id) {
        TraceableGroup traceableGroup = getById(id);
        if (ObjectUtil.isNull(traceableGroup)) {
            throw new AppException("溯源套餐不存在");
        }
        if (traceableGroup.getIsDel()) {
            throw new AppException("溯源套餐不存在");
        }
        return traceableGroup;
    }


}

